<?php
/**
 * main.php file
 * @author: luojinkui <378504632@qq.com>
 * @link: http://378504632@qq.com
 * @copyright: Copyright &copy; 2018 HangZhou Loojk2008 Technology Co., Ltd
 */

require 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Psr\Http\Message\ResponseInterface;
use React\EventLoop\Factory;
use React\HttpClient\Client as RClient;
use React\HttpClient\Response as RResponse;
use WyriHaximus\React\GuzzlePsr7\HttpClientAdapter;

//$factory = new React\Dns\Resolver\Factory();
//
//$cache = new MyCustomCacheInstance();
//$resolver = $factory->createCached('8.8.8.8', $loop, $cache);

$loop = Factory::create();

$x = function () use ($loop) {

    $list = [
        [
            'name' => 'taobao',
            'url' => 'https://world.taobao.com',
        ],

        [
            'name' => 'jd',
            'url' => 'https://www.jd.com',
        ],
        [
            'name' => 'vqq',
            'url' => 'https://v.qq.com/',
        ],
        [
            'name' => 'map qq',
            'url' => 'http://map.qq.com/',
        ],
        [
            'name' => '2345',
            'url' => 'https://www.2345.com/',
        ],
        [
            'name' => 'sohu',
            'url' => 'http://www.sohu.com/',
        ],
        [
            'name' => '58',
            'url' => 'http://hz.58.com/',
        ],
        [
            'name' => '7k7k',
            'url' => 'http://www.7k7k.com/',
        ],
        [
            'name' => '4399',
            'url' => 'http://www.4399.com/',
        ],

        [
            'name' => 'iqiyi',
            'url' => 'http://www.iqiyi.com/',
        ],

        [
            'name' => 'eastday',
            'url' => 'http://kankan.eastday.com/',
        ],
        [
            'name' => '166cai',
            'url' => 'https://888.166cai.cn/',
        ],

        [
            'name' => 'renrenche',
            'url' => 'https://www.renrenche.com/hz/ershouche/',
        ],
        [
            'name' => '163',
            'url' => 'http://news.163.com/',
        ],
        [
            'name' => 'autohome',
            'url' => 'https://www.autohome.com.cn/hangzhou/?pvareaid=100526',
        ],

        [
            'name' => 'baidu',
            'url' => 'https://www.baidu.com/s?wd=EventHttp&rsv_spt=1&rsv_iqid=0xfbb1a66000014c70&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=baiduhome_pg&rsv_enter=0&oq=libevent%2520%2526gt%253Bvent%253A%253AsetPriority&rsv_t=f39aorFhhb4pDMdERUxLGcd7I81miTgDMJozzP1Ncmuh9udEm8HkP%2FAnuguirMtU2Mp0&inputT=2282&rsv_pq=90bcc81400016727&rsv_sug3=50&rsv_sug1=31&rsv_sug7=000&rsv_sug4=2412&rsv_sug=1',
        ],
        [
            'name' => 'ctrip',
            'url' => 'http://you.ctrip.com/sight/hangzhou14/25559.html',
        ],
        [
            'name' => 'Nu',
            'url' => 'http://www.nu.nl/',
        ],
        [
            'name' => 'Yahoo!',
            'url' => 'http://www.yahoo.com/',
        ],
        [
            'name' => 'Duck Duck Go',
            'url' => 'http://www.duckduckgo.com/',
        ],
        [
            'name' => 'Blog',
            'url' => 'http://blog.wyrihaximus.net/',
        ],
    ];

    $guzzle = new Client([
        'handler' => HandlerStack::create(new HttpClientAdapter($loop)),
    ]);


    foreach ($list as $site)
    {

        $urlArr = parse_url($site['url']);
        $urlArr['path'] = isset($urlArr['path']) ? $urlArr['path'] : '';

        $hosts = gethostbynamel($urlArr['host']);

        $uri = $urlArr['scheme'] . '://' . $hosts[0] . $urlArr['path'];

        $uri = $site['url'];
        $name = $site['name'];
        $guzzle->getAsync($uri, [
            'stream' => TRUE,
            ['header' => ['host' => $urlArr['host']]],
        ])->then(function (ResponseInterface &$response) use (&$name, &$site, $loop, &$guzzle) {
            echo $name . ' completed' . PHP_EOL;
            //            echo $response->getStatusCode() . PHP_EOL;
            //            $body = $response->getBody();
            //            while (!$body->eof()) { // Reading from the body untill there is nothing more to read
            //                echo $body->read(1024);
            //            }

            //            echo $body->getContents();

            //            $tick = function () use (&$body, &$response, $name, $loop, &$tick) {
            //                do
            //                {
            //                    $data = $body->read(1024);
            //                    echo PHP_EOL;
            //                    echo '----------------------------------------';
            //                    echo PHP_EOL;
            //                    echo '|                Chunk                 |';
            //                    echo PHP_EOL;
            //                    echo '----------------------------------------';
            //                    echo PHP_EOL;
            //                } while ($data !== '');
            //                if (!$body->eof())
            //                {
            //                    $loop->futureTick($tick);
            //                }
            //                else
            //                {
            //                    unset($body, $name, $response, $tick, $data);
            //                    echo PHP_EOL;
            //                }
            //            };
            //            $loop->futureTick($tick);

            $guzzle = NULL;
            $response = NULL;
            $name = NULL;
            unset($guzzle, $response, $name);
        }, function (Exception &$error) use (&$name, &$site) {
            echo $name . ' error: ' . $error->getMessage() . PHP_EOL;
            $name = NULL;
            $site = NULL;
            $error = NULL;
            unset($name, $site, $error);
        });
    }
    $list = NULL;
    unset($list);
};

//$x();

$y = function () use (&$loop) {
    //    echo '22222',PHP_EOL;

    //     file_get_contents('https://www.baidu.com');
    $client = new RClient($loop);

    $request = $client->request('GET', 'http://www.baidu.com');

    $request->on('response', function (RResponse $response) use ($request) {
        //        var_dump($response->getHeaders());

        $response->on('data', function ($chunk) {
            //            echo $chunk;
        });

        $response->on('end', function () use ($request) {
            echo 'DONE' . PHP_EOL;
            $request->close();
        });
    });

    $request->on('error', function (\Exception $e) {
        echo $e;
    });

    $request->end();
    $request = NULL;
    $client = NULL;
    unset($request, $client);
};


$c = 1;
$loop->addPeriodicTimer(1.2, function () use (&$y, $x, &$c, &$loop) {
    if (intval($c / 30) > 1)
    {
        echo 'GC: ', gc_collect_cycles(), PHP_EOL;
        $c = 1;
        //        return;
    }

    $x();
    //        $y();


    $c += 1;

    unset($y, $x);
});

//$y();

$loop->addPeriodicTimer(5, function () {
    $memory = memory_get_usage() / 1024;
    echo $memory, PHP_EOL;
    $formatted = number_format($memory, 3) . 'K';

    if ($memory > 10000)
    {
        echo 'GC: ', gc_collect_cycles(), PHP_EOL;
    }
    echo "Current memory usage: {$formatted}\n";
});


$loop->run();